//
//  LoginViewModel.m
//  GLGW_Shoping
//
//  Created by yang on 2018/11/15.
//  Copyright © 2018年 yang. All rights reserved.
//

#import "LoginViewModel.h"
#import "LoginTableViewCell.h"
#import "LoginHeaderView.h"
#import "LoginActionTableViewCell.h"
#import "loginFootView.h"
#import "LoginModel.h"
#import <UMShare/UMShare.h>

@interface LoginViewModel ()<UITableViewDelegate,UITableViewDataSource,InputTextStrDelegate>{
    NSString * nameStr;
    NSString * passwordStr;
    GLGWButton * outBut;
}
@end

@implementation LoginViewModel

-(instancetype)initWithViewToViewModel:(UITableView *)tableView theSuperView:(UIView *)superView{
    if (self = [super initWithViewToViewModel:tableView theSuperView:superView]) {
        tableView.mj_footer.hidden = YES;
        tableView.mj_header.hidden = YES;
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableHeaderView = [self createHeaderView];
        tableView.tableFooterView = [self createFootView:tableView];
        [superView addSubview:tableView];
    }
    return self;
}

-(UIView *)createHeaderView{
    LoginHeaderView * headerView = [[LoginHeaderView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, kHeightProportion_In_iPhoneTriploid(110))];
    return headerView;
}

-(UIView *)createFootView:(UITableView *)selTableView{
    loginFootView * footView = [[loginFootView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, selTableView.height - kHeightProportion_In_iPhoneTriploid(330))];
    footView.Block_LoginFootView = ^(GLGWButton * _Nonnull f_but) {
        switch (f_but.tag) {
            case 200:{
                if (self.delegate && [self.delegate respondsToSelector:@selector(loginFootViewButAction:)]) {
                    [self.delegate loginFootViewButAction:f_but];
                }
            }
                break;
            case 201:{//qq
                [self getUserInfoForPlatform:UMSocialPlatformType_QQ];
            }
                break;
            case 202:{//weixin
                [self getUserInfoForPlatform:UMSocialPlatformType_WechatSession];
            }
                break;
                
            default:
                break;
        }
        
    };
    return footView;
}

- (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:nil completion:^(id result, NSError *error) {
        UMSocialUserInfoResponse *resp = result;
        // 第三方登录数据(为空表示平台未提供)
        // 授权数据
        NSLog(@" uid: %@", resp.uid);
        NSLog(@" openid: %@", resp.openid);
        NSLog(@" accessToken: %@", resp.accessToken);
        NSLog(@" refreshToken: %@", resp.refreshToken);
        NSLog(@" expiration: %@", resp.expiration);
        
        // 用户数据
        NSLog(@" name: %@", resp.name);
        NSLog(@" iconurl: %@", resp.iconurl);
        NSLog(@" gender: %@", resp.unionGender);
        
        // 第三方平台SDK原始数据
        NSLog(@" originalResponse: %@", resp.originalResponse);
        if (resp) {
            [self requestLoginData:platformType theOpenId:resp];
//            RegistereViewController * regisesVC = [RegistereViewController new];
//            regisesVC.reg_type = RegisterePushType_BindingPhone;
//            if (platformType == UMSocialPlatformType_QQ) {
//
//            } else {
//
//            }
//            [self.navigationController pushViewController:regisesVC animated:YES];
        }
    }];
}

#pragma mark --- 数据请求
-(void)requestLoginData:(UMSocialPlatformType)p_type theOpenId:(UMSocialUserInfoResponse *)resp{
//    kThridLogin
    NSDictionary * parDic = @{@"openId":koString(resp.openid),@"token":koString(resp.accessToken)};
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kThridLogin] lodingView:nil lodingTextString:@"" isLoding:YES parameters:parDic success:^(id  _Nullable response) {
        LoginModel * l_Model = [LoginModel yy_modelWithJSON:response];
        if (l_Model.code == 0) {
            switch (p_type) {
                case UMSocialPlatformType_QQ:{
                    if (l_Model.data.regeditTypes.isQQregist == 1) {
                        if (self.delegate && [self.delegate respondsToSelector:@selector(bindingIdentityType:theToken:theOpenId:)]) {
                            [self.delegate bindingIdentityType:3 theToken:resp.accessToken theOpenId:resp.openid];
                        }
                    }else{
                        NSData * userData = [NSKeyedArchiver archivedDataWithRootObject:l_Model];
                        self.userInforData = userData;
                        self.userId = l_Model.data.userId;
                        //            LoginModel * l_Modle = [NSKeyedUnarchiver unarchiveObjectWithData:self.userInforData];
                        if (self.delegate && [self.delegate respondsToSelector:@selector(loginSuccess)]) {
                            [self.delegate loginSuccess];
                        }
                    }
                }
                    break;
                case UMSocialPlatformType_WechatSession:{
                    if (l_Model.data.regeditTypes.isWxRegist == 1) {
                        if (self.delegate && [self.delegate respondsToSelector:@selector(bindingIdentityType:theToken:theOpenId:)]) {
                            [self.delegate bindingIdentityType:2 theToken:resp.accessToken theOpenId:resp.openid];
                        }
                    }else{
                        NSData * userData = [NSKeyedArchiver archivedDataWithRootObject:l_Model];
                        self.userInforData = userData;
                        self.userId = l_Model.data.userId;
                        //            LoginModel * l_Modle = [NSKeyedUnarchiver unarchiveObjectWithData:self.userInforData];
                        if (self.delegate && [self.delegate respondsToSelector:@selector(loginSuccess)]) {
                            [self.delegate loginSuccess];
                        }
                    }
                }
                    break;
                    
                default:
                    break;
            }
        }
    } failure:^(NSError * _Nullable error) {
        
    }];
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 2) {
        return kHeightProportion_In_iPhoneTriploid(94);
    }else{
        return kHeightProportion_In_iPhoneTriploid(62);
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BaseTableViewCell * cell;
    switch (indexPath.row) {
        case 0:
        case 1:{
            NSString * indexStr = NSStringFromClass([LoginTableViewCell class]);
            LoginTableViewCell *cell_input = [tableView dequeueReusableCellWithIdentifier:indexStr];
            if (!cell_input) {
                cell_input = [[LoginTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indexStr theLoginRow:indexPath.row];
            }
            cell_input.delegate = self;
            cell = cell_input;
        }
            break;
        case 2:{
            LoginActionTableViewCell * cell_action = [LoginActionTableViewCell cellWithTableView:tableView];
            outBut =  cell_action.actionBut;
            [outBut addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
            cell = cell_action;
        }
            break;
            
        default:
            break;
    }
    return cell;
}
#pragma mark --- action

-(void)loginAction{
    DLog(@"登陆");
    NSDictionary * preDic = @{@"username":koString(nameStr),@"password":koString(passwordStr)};
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kLogin] lodingView:nil lodingTextString:@"" isLoding:YES parameters:preDic success:^(id  _Nullable response) {
        LoginModel * loginModel = [LoginModel yy_modelWithJSON:response];
        if (loginModel.code == 0) {
            NSData * userData = [NSKeyedArchiver archivedDataWithRootObject:loginModel];
            self.userInforData = userData;
            self.userId = loginModel.data.userId;
//            LoginModel * l_Modle = [NSKeyedUnarchiver unarchiveObjectWithData:self.userInforData];
            if (self.delegate && [self.delegate respondsToSelector:@selector(loginSuccess)]) {
                [self.delegate loginSuccess];
            }
        }
    } failure:^(NSError * _Nullable error) {
        
    }];
    
}

#pragma mark --- InputTextStrDelegate
-(void)inputNameStr:(NSString *)name_str thePassStr:(NSString *)p_str{
    nameStr = name_str;
    passwordStr = p_str;
    if (nameStr.length>0 && passwordStr.length>0) {
        outBut.backgroundColor = kColor_Rule_Yellow;
        outBut.enabled = YES;
    }else{
        outBut.backgroundColor = [UIColor colorWithHexString:@"#CCCCCC"];
        outBut.enabled = NO;
    }
}

@end
